package vn.edu.ptithcm.pim.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.common.bean.PaginationObject;
import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.Paginations;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Application;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.dom.Task;
import vn.edu.ptithcm.pim.query.ProjectQuery;
import vn.edu.ptithcm.pim.service.ActivityLogService;
import vn.edu.ptithcm.pim.service.EmployeeFunctionInProjectService;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.ProjectStatusService;
import vn.edu.ptithcm.pim.service.ResourceService;
import vn.edu.ptithcm.pim.service.TaskService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class ProjectController extends SimpleFormController {

	private ProjectService projectService;
	private UserService userService;
	private EmployeeFunctionInProjectService employeeFunctionInProjectService;
	private ProjectStatusService projectStatusService;
	private int ITEMS_PER_PAGE = 5;
	private List<Integer> itemsPerPage = new ArrayList<Integer>();
	private ActivityLogService activityLogService;
	private ResourceService resourceService;
	private TaskService taskService;

	Logger log = Logger.getLogger(ProjectController.class);

	public ProjectController() {
		super();
		setSessionForm(true);
		setCommandName("projectQuery");
		setCommandClass(ProjectQuery.class);
		setFormView(UrlConstants.PROJECTS_URL);
		setSuccessView(UrlConstants.PROJECTS_URL);
		this.itemsPerPage.add(5);
		this.itemsPerPage.add(10);
		this.itemsPerPage.add(20);
		this.itemsPerPage.add(30);
		this.itemsPerPage.add(50);
		this.itemsPerPage.add(75);
		this.itemsPerPage.add(100);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ProjectQuery projectQuery = new ProjectQuery();
		return projectQuery;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	private void pagingProject(HttpServletRequest request,
			ProjectQuery projectQuery) {
		try {
			PaginationObject paging = null;
			List<Project> projects = new ArrayList<Project>();
			int total = 0;

			int currentPage = ParamUtil.getInteger(request,
					Paginations.CURRENT_PAGE_NUM, 1);
			int pageSize = ParamUtil.getInteger(request, Paginations.PAGE_SIZE,
					ITEMS_PER_PAGE);

			total = projectService.countByQuery(projectQuery);
			paging = new PaginationObject("projectPaging", total);
			paging.setItemsPerPage(itemsPerPage);
			paging.paging(currentPage, pageSize);

			int max = paging.getEndIndex() - paging.getStartIndex();
			projects.addAll(projectService.findByQuery(projectQuery, max,
					paging.getStartIndex()));

			request.setAttribute("projects", projects);
			request.setAttribute("paging", paging);
			request.setAttribute("total", total);

			log.info("results : " + projects.size() + " projects");
			log.info("total : " + total);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		log.info("submit");
		ProjectQuery query = (ProjectQuery) command;
		String cmd = ParamUtil.getString(request, "cmd", "");

		log.info("search key : " + query.getSearchKey());
		log.info("status : " + query.getStatusId());

		if ("searchProjects".equals(cmd)) {
			log.info("cmd=searchProjects");
			pagingProject(request, query);
		} else if ("deleteProjects".equals(cmd)) {
			log.info("cmd=deleteProjects");
			if (query.getProjectIds().size() > 0) {
				for (int i = 0; i < query.getProjectIds().size(); ++i) {
					Long projectId = new Long(query.getProjectIds().get(i));
					activityLogService.deleteByProjectId(projectId);
					resourceService.deleteByProjectId(projectId);
					List<Task> tasks = taskService
							.getAllTasksHasAttachedfiles(projectId);
					for (Task task : tasks) {
						resourceService.deleteByTaskId(task.getTaskid());
					}
					projectService.deleteById(projectId);
				}
			}
			pagingProject(request, query);
		}

		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));

			boolean isAdmin = userService.isAdmin(loginName);
			bean.put("isAdmin", isAdmin);

			List<Project> projects = new ArrayList<Project>();

			if (isAdmin) {
				bean.put("statuses", projectStatusService.getAll());

				if (request.getAttribute("projects") == null) {
					
					String searchKey = ParamUtil.getString(request,
							"key", "");
					Long statusId = ParamUtil.getLong(request, "status", 0);

					ProjectQuery query = new ProjectQuery();
					query.setSearchKey(searchKey);
					query.setStatusId(statusId);

					log.info("search key : " + query.getSearchKey());
					log.info("status : " + query.getStatusId());

					pagingProject(request, query);

				}

				projects = (List<Project>) ParamUtil.getObject(request,
						"projects", null);

				bean.put("pagingUrl", request.getRequestURL().toString());

				bean.put("paging", ParamUtil.getObject(request, "paging", null));

				bean.put("total", ParamUtil.getObject(request, "total", null));

				bean.put("itemsPerPage", ITEMS_PER_PAGE);

			} else {
				projects = employeeFunctionInProjectService
						.getProjectsByVisa(userService.getVisa(loginName));
			}

			
			bean.put("projects", projects);
			bean.put("countList", projects.size());

			List<Application> applications = userService
					.getApplications(loginName);

			String selectedPage = "";
			String viewURL = request.getRequestURI();

			for (Application p : applications) {
				String friendlyUrl = p.getFriendlyurl();
				if (viewURL.indexOf(friendlyUrl) != -1) {
					selectedPage = friendlyUrl;
					break;
				}
			}

			bean.put("selectedPage", selectedPage);
			bean.put("applications", applications);

			String currentURL = request.getRequestURL().toString();
			int indexCurrentPage = currentURL.indexOf("?currentPage");

			if (indexCurrentPage != -1) {
				currentURL = currentURL.substring(0, indexCurrentPage);
			}
			bean.put("currentURL", currentURL);

			String pageURL = currentURL;
			int indexPage = pageURL.indexOf("?");
			if (indexPage != -1) {
				pageURL = pageURL.substring(0, indexPage);
			}

			bean.put("pageURL", pageURL);

			request.setAttribute("bean", bean);
		} else {
			String redirectLink = UrlConstants.PROJECTS_URL + UrlConstants.HTM;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public EmployeeFunctionInProjectService getEmployeeFunctionInProjectService() {
		return employeeFunctionInProjectService;
	}

	public void setEmployeeFunctionInProjectService(
			EmployeeFunctionInProjectService employeeFunctionInProjectService) {
		this.employeeFunctionInProjectService = employeeFunctionInProjectService;
	}

	public ProjectStatusService getProjectStatusService() {
		return projectStatusService;
	}

	public void setProjectStatusService(
			ProjectStatusService projectStatusService) {
		this.projectStatusService = projectStatusService;
	}

	/**
	 * @return the activityLogService
	 */
	public ActivityLogService getActivityLogService() {
		return activityLogService;
	}

	/**
	 * @param activityLogService
	 *            the activityLogService to set
	 */
	public void setActivityLogService(ActivityLogService activityLogService) {
		this.activityLogService = activityLogService;
	}

	/**
	 * @return the resourceService
	 */
	public ResourceService getResourceService() {
		return resourceService;
	}

	/**
	 * @param resourceService
	 *            the resourceService to set
	 */
	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	/**
	 * @return the taskService
	 */
	public TaskService getTaskService() {
		return taskService;
	}

	/**
	 * @param taskService
	 *            the taskService to set
	 */
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

}
